const asyncHandler = require("../utils/asyncHandler");
const Post = require("../models/Post");
const { success, error } = require('../utils/response')

// 创建文章
exports.createPost = asyncHandler(async (req, res) => {
    const { title, content, tags = [], published = false, coverImageUrl = "" } = req.body;
    const post = await Post.create({
        title,
        content,
        tags,
        published,
        coverImageUrl,
        author: req.user._id,
        publishedAt: published ? new Date() : undefined,
    });

    return success(res, post, '创建成功')
});

// 更新文章
exports.updatePost = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const { title, content, tags, published, coverImageUrl } = req.body;

    const post = await Post.findById(id);
    if (!post)
        return error(res, '文章不存在')

    if (title !== undefined) post.title = title;
    if (content !== undefined) post.content = content;
    if (Array.isArray(tags)) post.tags = tags;
    if (coverImageUrl !== undefined) post.coverImageUrl = coverImageUrl;

    if (published !== undefined) {
        if (!post.published && published) post.publishedAt = new Date();
        post.published = published;
    }

    await post.save();
    return success(res, post, '更新成功')
});

// 删除文章
exports.deletePost = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const post = await Post.findById(id);
    if (!post)
        return error(res, '文章不存在')

    await post.deleteOne();
    return success(res, null, '已删除')
});

// 获取文章列表（分页 + 搜索 + 过滤）
exports.listPosts = asyncHandler(async (req, res) => {
    const {
        page = 1,
        limit = 10,
        q = "",
        tag,
        authorId,
        published = "true",
        sort = "latest", // latest | oldest
    } = req.query;

    const filter = {};
    if (published !== "all") {
        filter.published = published === "true";
    }
    if (q) {
        filter.$or = [
            { title: new RegExp(q, "i") },
            { content: new RegExp(q, "i") },
        ];
    }
    if (tag) filter.tags = tag;
    if (authorId) filter.author = authorId;

    const sortOption = sort === "oldest" ? { createdAt: 1 } : { createdAt: -1 };

    const skip = (Number(page) - 1) * Number(limit);
    const [items, total] = await Promise.all([
        Post.find(filter)
            .populate("author", "username avatarUrl role")
            .sort(sortOption)
            .skip(skip)
            .limit(Number(limit)),
        Post.countDocuments(filter),
    ]);

    const data = {
        items,
        pagination: {
            page: Number(page),
            limit: Number(limit),
            total,
            pages: Math.ceil(total / Number(limit)),
        },
    }
    return success(res, data)
});

// 通过 slug 获取文章（游客只可见已发布；作者/管理员可见草稿）
exports.getPostBySlug = asyncHandler(async (req, res) => {
    const { slug } = req.params;
    const post = await Post.findOne({ slug }).populate("author", "username avatarUrl role");

    if (!post) return error(res, '文章不存在')

    // 未发布时，只有作者或管理员可看
    if (!post.published) {
        const isOwner = req.user && String(req.user._id) === String(post.author._id);
        const isAdmin = req.user?.role === "admin";
        if (!isOwner && !isAdmin)
            return error(res, '无权限查看该草稿')
    }

    return success(res, post)
});
